package com.xjwlmq.dx.servlet;

import com.alibaba.fastjson.JSON;
import com.xjwlmq.dx.dao.impl.StudentDaoImpl;
import com.xjwlmq.dx.dao.impl.SubjectDaoImpl;
import com.xjwlmq.dx.entity.Student;
import com.xjwlmq.dx.util.BaseDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @ClassName StudentListServlet
 * @Description Servlet: 接收、处理并响应用户请求
 * @Author 12994
 * @Date 2024/9/29 10:49
 * @Version 1.0
 **/
@WebServlet("/userList")
public class StudentListServlet extends HttpServlet {
    /**
     * @param req  请求
     * @param resp 返回
     * @throws ServletException
     * @throws IOException
     */
    StudentDaoImpl studentDao = new StudentDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // super.service(req, resp);
        // 设置响应编码格式
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html:charset=UTF-8");
        // 设置跨域响应头（解决跨域问题）
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有源
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        // 获得用户列表
        if (req.getParameter("studentNo") != null) {
            ArrayList<Student> students = studentDao.getStudentList(Integer.parseInt(req.getParameter("studentNo")));
            String stustr = JSON.toJSONString(students);
            resp.getWriter().write(stustr);
        } else {
            ArrayList<Student> students = studentDao.getStudentList();
            String stustr = JSON.toJSONString(students);
            resp.getWriter().write(stustr);
        }
    }
}
